package com.demo.study.algorithm.leetcode.array.easy;

import org.junit.Test;

import java.util.HashMap;
import java.util.Map;

/**
 * LT1
 * <a href="https://leetcode.cn/problems/two-sum">两数之和</a>
 *
 * @author Baymax
 * @since 2024-11-17
 */
public class LT1 {
    @Test
    public void run() {

    }

    public int[] twoSum(int[] nums, int target) {
        int[] result = new int[2];
        for (int i = 0; i < nums.length; i++) {
            for (int j = i + 1; j < nums.length; j++) {
                if (nums[i] + nums[j] == target) {
                    result[0] = i;
                    result[1] = j;
                }
            }
        }
        return result;
    }

    /*
    作者：画手大鹏
    链接：https://leetcode.cn/problems/two-sum/solutions/6873/jie-suan-fa-1-liang-shu-zhi-he-by-guanpengchn/
    来源：力扣（LeetCode）
    著作权归作者所有。商业转载请联系作者获得授权，非商业转载请注明出处。
     */
    public int[] twoSum2(int[] nums, int target) {
        Map<Integer, Integer> map = new HashMap<>();
        for(int i = 0; i< nums.length; i++) {
            if(map.containsKey(target - nums[i])) {
                return new int[] {map.get(target-nums[i]),i};
            }
            map.put(nums[i], i);
        }
        throw new IllegalArgumentException("No two sum solution");
    }


}
